study.ajaxQueue = [];
$.ajax = function(args) {
    args.attempts = 0;
    study.ajaxQueue.push(args);
};

study.host = '{{host}}';

study.serializeTagArray = function(ar) {
    var ar2 = [];
    for (var i = 0, j = ar.length; i < j; i++) {
	var str = ar[i];
	str = encodeURIComponent(str);
	ar2.push(str)
    }
    return ar2;
};

study.serialize = function(ar) {
    var ar2 = [];
    var t = {};
    for (var i = 0, j = ar.length; i < j; i++) {
	var obj = ar[i];
	if (typeof(t[obj.name]) == 'undefined') {
	    t[obj.name] = [];
	}
	var t2 = t[obj.name];
	t2.push(obj.value);
    }
    for (var i = 0, j = ar.length; i < j; i++) {
	var obj = ar[i];
	if (typeof(t[obj.name]) != 'undefined') {
	    var t2 = t[obj.name];
	    t2 = t2.join(',');
	    ar2.push(encodeURIComponent(obj.name) + '=' + encodeURIComponent(t2));
	    delete(t[obj.name]);
	}
    }
    return ar2.join("&");
};

study.ajax_do = function() {
    if (study.ajaxQueue.length == 0) {
	setTimeout(study.ajax_do,2);
	study.adjustHeight();
	return;
    }
    var args = study.ajaxQueue[0];
    var params = {};
    if (args.dataType == 'json') {
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    } else {
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    }
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    if ((args.type == 'GET') && (typeof(args.data) == 'undefined')) {
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    } else {
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	var post_data = '';
	if (args.data) {
	    var tags = '';
	    if (typeof(args.data.tags) != 'undefined') {
		args.data.tags = study.serializeTagArray(args.data.tags);
	    }
	    if (typeof(args.data.length) == 'undefined') {
		post_data = gadgets.io.encodeValues(args.data);
	    } else {
		post_data = study.serialize(args.data);
	    }
	}
	params[gadgets.io.RequestParameters.POST_DATA] = post_data;
    }

    var url = args.url;
    if (url.search(/^https?:/i) == -1) {
	url = 'http://{{host}}' + args.url;
    }
    var sep = '?';
    if (url.indexOf("?") > -1) {
	sep = '&';
    }
    var ts = new Date().getTime();
    url = [url, sep, 'nocache=', ts].join("");
    var callback = function(r) {
	// if failed, retry
	if ((r.errors.length > 0) || (parseInt(r.rc) != 200)) {
	    if (args.attempts > 20) {
		if (study.host.search(/dyndns/) >= 0) {
		    $('#content').html('<p>makeRequest failed 20 times?  Look at the log file.</p>');
		} else {
		    $('#content').html('<p>We apologize for your inconvenience.  An error happened.  We will investigate it.  Please try again later.</p>');
		}
		study.ajaxQueue = [];
		setTimeout(study.ajax_do,1);
		return;
	    }
	    args.attempts = args.attempts + 1;
	    study.ajax_do();
	} else {
	    study.ajaxQueue.shift();
	    if (args.success) {
		args.success(r.data);
	    }
	    study.ajax_do();
	}
    };
    gadgets.io.makeRequest(url,callback,params);
};

$.get = function(url,data,callback,type) {
    var args = {};
    args.url = url;
    if (typeof(data) != 'undefined') { args.data = data; }
    if (typeof(callback) != 'undefined') { args.success = callback; }
    if (typeof(type) != 'undefined') { args.type = type; }
    $.ajax(args);
};

$.getJSON = function(url,data,callback) {
    var args = {};
    args.url = url;
    if (typeof(data) != 'undefined') { args.data = data; }
    if (typeof(callback) != 'undefined') { args.success = callback; }
    args.dataType = 'json';
    $.ajax(args);
};

jQuery.fn.load = function(url,data,callback) {
    var args = {};
    args.url = url;
    args.dataType = 'html';
    var that = this;
    if (typeof(data) != 'undefined') { args.data = data; }
    args.success = function(data) {
	that.html(data);
	if (typeof(callback) != 'undefined') {
	    callback();
	}
    }
    $.ajax(args);
};

setTimeout(study.ajax_do,1);

study.shareURL_callback = function(data) {
    study.renderSetList(data,true);
};
study.shareURL = function(e) {
    var url = $('#shareURL_input').val();
    url = jQuery.trim(url);
    if ((url != '') && (url.search(/\bshare\b/) > -1)) {
	var that = this;
	$(this).val('Please wait').disable();
	$.ajax({'url': url, 'success': function() { $('#shareURL_input').val(''); $(that).val('Study').enable(); study.refreshSetList(true); }});
    } else {
	$('#shareURLContainerDiv_error').text('Please provide a valid URL and click the Study button again.');
    }
};

study.getDisplayName = function(type,callback) {
    var req = opensocial.newDataRequest();
    if (type == 'viewer') {
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER),'viewer');
    } else {
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER),'owner');
    }
    req.send(callback);
};

study.addUser_social = function() {
    var prefs = new gadgets.Prefs();
    var userCreated = prefs.getBool('userCreated');
    if (! userCreated) {
	study.getDisplayName('viewer',function(r) {
	    var viewer = r.get('viewer').getData();
	    var displayName = viewer.getDisplayName();
	    $.ajax({'url': '/social/updateDisplayName.json', 'type': 'POST', 'data': {'displayName': displayName}, 'success': function(){
		prefs.set('userCreated',true);
	    }});
	});
    }
};

study.gotoCanvasView = function(e) {
    e.preventDefault();
    var canvas = gadgets.views.getSupportedViews()['canvas'];
    gadgets.views.requestNavigateTo(canvas);
    return false;
};

study.init = function() {
    study.social = true;
    study.socialView = gadgets.views.getCurrentView().getName();
    study.addUser_social();
    if (study.socialView == 'canvas') {
	$('#header_bar').removeClass('hideMe');
	$("#addset").click(study.renderAddSetForm);
	$("#usageHistoryLink").click(study.displayUsageHistoryPage);
	$('#searchbtn').click(study.search);
	$('#homeLink').click(function(e) { e.preventDefault(); study.refreshSetList(true); return false;});
	// study.fetchTemplate('studyTableTemplate');
    } else {
	$('#shareURLContainerDiv').removeClass('hideMe');
	$('#shareURL_form').submit(study.doNothing_handler);
	$('#shareURL_btn').click(study.shareURL);
	$('<a href="/" id="switchToCanvas">Go to canvas view!</a>').appendTo('#shareURLContainerDiv');
	$('#switchToCanvas').click(study.gotoCanvasView);
	// study.fetchTemplate('studyTableTemplate');
    }
    study.refreshSetList(true);
};

gadgets.util.registerOnLoadHandler(study.init);
